import { Toast } from "antd-mobile";
import { createHashRouter, redirect } from "react-router-dom";
import App from "./App";
import Home from "./pages/home";
import Login from "./pages/login/index";
import Pratice from "./pages/pratice";
import Qdtest from "./pages/qdtest";
import Quick from "./pages/quick";
import Register from "./pages/register";
import Toggle from "./pages/toggle";
import User from "./pages/user";
import { ApiGetHomeData, ApiQuickData } from "./utils/api";
import { isLogin } from "./utils/utils";

const router = createHashRouter([
  {
    path: "/",
    element: <App></App>,
    errorElement: <>404 页面丢失</>,
    // loader(params) {
    //   if (params.request.url === "http://127.0.0.1:5173/") {
    //     return redirect("/home");
    //   }
    // },
    children: [
      //首页
      {
        // 设置index为true的时候，path就不需要设置，该选项就变成首页/
        // path: "home",
        index: true,
        element: <Home />,
        loader() {
          if (!isLogin()) {
            return redirect("/login");
          }
          let getData = async () => {
            let res = await ApiGetHomeData();
            if (res.errCode !== 0) {
              Toast.show({
                icon: "fail",
                content: res.message,
              });
              return;
            }
            return res.data;
          };
          return { getData };
        },
      },
      //快速刷题
      {
        path: "quick",
        element: <Quick />,
        loader() {
          let quickData = async () => {
            let res = await ApiQuickData();
            // console.log("quick的数据:",res);
            if (res.errCode !== 0) {
              Toast.show({
                icon: "fail",
                content: res.message,
              });
              return;
            }
            return res.data;
          };
          return { quickData };
        },
      },
      //练习题目
      {
        path: "pratice",
        element: <Pratice />,
      },
      //练习问答
      {
        path: "test",
        element: <Qdtest />,
      },
      //用户信息
      {
        path: "user",
        element: <User />,
        loader() {
          if (!isLogin()) {
            Toast.show({
              icon: "fail",
              content: "未登录",
            });
            return redirect("/login");
          }
        },
      },
      //登录
      {
        path: "login",
        element: <Login />,
      },
      //注册
      {
        path: "register",
        element: <Register />,
      },
      //切换考试科目1
      {
        path: "toggle",
        element: <Toggle />,
      },
    ],
  },
]);
export default router;
